import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-api-control',
	templateUrl: './api.component.html',
})
export class ApiControlComponent implements OnInit {
	
	validatorOptions = {
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			interfaceName:{
				validators: {
					notEmpty: {
						message: '请输入接口名称'
					}
				}
			},
			interfaceKey:{
				validators: {
					notEmpty: {
						message: '请选择输入接口标识'
					}
				}
			},
			lockStatus: {
				validators: {
					notEmpty: {
						message: '请选择用户状态'
					}
				}
			},
		}
	}
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	tableSearch:any = {
		searchKey:''
	}
	startTime:string='';
	endTime:string='';
	apiList:any; //用户数据
	interfaceKey:string = ''; //接口ID
	interfaceName:string = '';  //接口名称
	apiControlFrom:any  = {
		id:null,
		interfaceName:'',
		interfaceKey:'',
		remark:'',
		lockStatus:'1'
	}
	formType:string = 'new';
	
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute ) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage||1;
		});
	}
	//擦除接口所选值
	delApi(){
		this.interfaceName = '';
		this.interfaceKey = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#apiSelect2').val("");
		$("#select2-apiSelect2-container").empty();
		$("#select2-apiSelect2-container").attr("title","");
		$("#select2-apiSelect2-container").prepend(str);
		this.load();
	}
	//初始化select2 选项
	selectApi(){
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				$("#apiSelect2").select2({
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.apiList,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.interfaceName = data.text;
		        	  	that.interfaceKey = data.id;
		        });
			})
		})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//拉取api数据
	initAllApi(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("apiConfig/getAllApiList.html",null).subscribe(data=> {
				if(data.success){
					var apiList = data.data;
		        	var selectdata = [];
		        	for(var i = 0 ; i < apiList.length ; i++) {
		        		var obj = {
		        			id:apiList[i].interfaceKey,
		        			text:apiList[i].interfaceName,
		        		}
		        		selectdata[i] = obj;
		        	}
				}
				that.apiList = selectdata;
				resolve();
			})
		})
	}
	// 接收子组件传递过来的数据 
	getSelectTableTime(time){
		this.startTime=time.startTime;
		this.endTime=time.endTime;
	}
	ngOnInit(){
//		this.initAllApi().then(()=>{
//			this.selectApi();
			this.load();
//		});
	}
	//table刷新
    refresh(){
    	this.load();
    }
	//表格搜索
	table_search(){
		this.curPage = 1;
		this.load();
	}
	//初始化加载list数据
	load(){
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				apiId:this.interfaceKey,
				startTime:this.startTime,
				endTime:this.endTime,
				searchKey:common.stringTrim(this.tableSearch.searchKey)
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("apiConfig/queryApiList.html", reqdata).subscribe(data => {
			if(data.isSuccess){
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}else{
				this.jsonApiService.message(data.message);
			}
		})
	}
	//删除
	delRow(row){
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			this.jsonApiService.http_obj("apiConfig/deleteApiConfig.html",{id:row.id}).subscribe(data=>{
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	/*
	 * 新增
	 */
	table_add(modal){
		this.modalClose(modal);
		modal.show();
		this.formType = 'new';
	}
	/*
	 * 状态change回调
	 */
	lockStatusChange(val){
		this.apiControlFrom.lockStatus = val;
	}
	/*
	 * 编辑
	 */
	editRow(row,modal){
		modal.show();
		this.apiControlFrom.configId = row.id;
		this.formType = 'updata';
		this.jsonApiService.http_obj("apiConfig/queryApiConfigById.html",{id:row.id}).subscribe(data=>{
			if(data.data){
				for(let item in this.apiControlFrom){
					this.apiControlFrom[item] = data.data[item];
					if(item == 'lockStatus'){
						this.apiControlFrom[item] = data.data[item]+'';
					}
				}
			}
		})
		
	}
	
	/*
	 * 关闭弹窗
	 */
	modalClose(modal){
		modal.hide();
		$("#apiControlFrom").data('bootstrapValidator').resetForm();
		this.apiControlFrom.id = '';
		this.apiControlFrom.interfaceName = '';
		this.apiControlFrom.interfaceKey = '';
		this.apiControlFrom.remark = '';
		this.apiControlFrom.lockStatus = '1';
		$('#limitStartTime').val('');
		$('#limitEndTime').val('');
	}
	/*
	 * form提交
	 */
	apiControlSubmit(modal){
		$('#apiControlFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#apiControlFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			let url;
			if(this.formType == 'new'){
				url = "apiConfig/addApiConfig.html";
			}else if(this.formType == 'updata'){
				url = "apiConfig/updateApiConfig.html";
			}
			this.jsonApiService.http_obj(url,this.apiControlFrom).subscribe(data=> {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
					this.modalClose(modal);
				}
			})
		}
	}

}